import { Injectable } from '@nestjs/common';
import { ofetch } from 'ofetch';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AuthingService {
  private readonly clientId: string;
  private readonly clientSecret: string;
  private readonly redirectUri: string;
  private readonly baseUrl: string;

  constructor(private configService: ConfigService) {
    this.clientId = this.configService.get<string>('AUTHING_CLIENT_ID')||'';
    this.clientSecret = this.configService.get<string>('AUTHING_CLIENT_SECRET')||'';
    this.redirectUri = this.configService.get<string>('AUTHING_REDIRECT_URI')||'';
    this.baseUrl = this.configService.get<string>('AUTHING_BASE_URL')||'';
  }

  async getToken(code: string) {
    const data = await ofetch(`${this.baseUrl}/oidc/token`, {
        method: 'POST',
        body: new URLSearchParams({
          client_id: this.clientId,
          client_secret: this.clientSecret,
          grant_type: 'authorization_code',
          redirect_uri: this.redirectUri,
          code: code,
        }),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        }
      });
      return data;
  }
  
  async getUser(access_token: string) {
    const data = await ofetch(`${this.baseUrl}/api/v3/get-profile?withCustomData=true&withIdentities=true&withDepartmentIds=true`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json, text/plain, */*',
          'authorization': access_token,  
          'x-authing-app-id': this.clientId,
        }
      })
      return data;
  }
}